package com.zhanghe.study.io.old;


import java.io.IOException;
import java.io.RandomAccessFile;

/**
 * 随机访问   既可以输出流，也可以是输入流  支持从任意位置读取、写入
 * mode参数
 * r 只读
 * rw 读写
 * rwd 读写  同步文件内容的更新
 * rws 读写  同步文件内容和元数据的更新
 */
public class TestRandomAccessFile {
    public static void main(String[] args) throws IOException {
//        test();
        random1();
    }

    /**
     * 读写
     */
    private static void test(){
        RandomAccessFile readFile= null;
        RandomAccessFile writeFile = null;
        try {
            readFile = new RandomAccessFile("hello.txt","r");
            writeFile = new RandomAccessFile("hello1.txt","rw");

            byte[] b = new byte[20];
            int len;
            while ((len = readFile.read(b)) != -1){
                writeFile.write(b,0,len);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                readFile.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                writeFile.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    // 从第4位之后开始覆盖
    private static void random() throws IOException {
        RandomAccessFile file = new RandomAccessFile("hello.txt","rw");

        file.seek(4);
        file.write("zhanghe".getBytes());
        file.close();
    }

    private static void random1() throws IOException {
        RandomAccessFile file = new RandomAccessFile("hello.txt","rw");
        file.seek(4); // 指针移到第4位
        byte[] b = new byte[20];
        int len;
        StringBuilder sb = new StringBuilder();
        while ((len = file.read(b)) != -1){
            sb.append(new String(b,0,len));
        }
        file.seek(4); // 重新把位置移到4
        file.write("lulu".getBytes()); // 写入
        file.write(sb.toString().getBytes()); // 将之前的数据写入
        file.close();
    }
}
